package com.example.demoexample.activity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.demoexample.MyService;
import com.example.demoexample.R;
import com.example.demoexample.aidl.MyAIDLService;
import com.example.demoexample.service.AidlService;
import com.example.demoexample.service.MessageService;
import com.example.demoexample.service.MyIntentService;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ServiceActivity extends AppCompatActivity {
    private static final String TAG = "ServiceActivity";
    @BindView(R.id.btn_bind)
    Button btnBind;
    @BindView(R.id.btn_unbind)
    Button btnUnbind;
    @BindView(R.id.btn_sendmsg)
    Button btnSendmsg;
    private ServiceConnection serviceConnection;

    private Messenger mService;
    /**
     * Flag indicating whether we have called bind on the service.
     */
    boolean mBound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                MyService service1 = ((MyService.MyBinder) service).getService();
                Log.e(TAG, "service1.getCount() = " + service1.getCount());
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, serviceConnection, Service.BIND_ABOVE_CLIENT);
        startService(intent);

        ServiceConnection serviceConnection2 = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                MyAIDLService myAIDLService = MyAIDLService.Stub.asInterface(service);
                try {
                    int plus = myAIDLService.plus(3, 5);
                    String upperCase = myAIDLService.toUpperCase("hello world");
                    Log.e(TAG,"plus = " + plus + "upperCase = "+ upperCase);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        Intent intent3 = new Intent(this, AidlService.class);
        bindService(intent3, serviceConnection2, Service.BIND_AUTO_CREATE);
//        startService(intent3);

        Intent intent4 = new Intent(this, MyIntentService.class);
        intent.putExtra(MyIntentService.EXTRA_PARAM1,"hello");
        intent.putExtra(MyIntentService.EXTRA_PARAM2,"world");
        MyIntentService.startActionFoo(this,"hello","world");
    }

    private ServiceConnection serviceConnection2 = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            mBound = false;
        }
    };

    /**
     * 用于接收服务器返回的信息
     */
    private Messenger mRecevierReplyMsg = new Messenger(new ReceiverReplyMsgHandler());
    public class ReceiverReplyMsgHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MessageService.MSG_SAY_HELLO:
                    Log.e(TAG, "receiver message from service:" + msg.getData().getString("reply"));
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }

        }
    }

    public void sayHello(View v) {
        if (!mBound) return;
        // 创建与服务交互的消息实体Message
        Message msg = Message.obtain(null, MessageService.MSG_SAY_HELLO, 0, 0);
        msg.replyTo = mRecevierReplyMsg;
        try {
            //发送消息
            mService.send(msg);
            Log.e(TAG, "sayHello:");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(serviceConnection);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.btn_bind, R.id.btn_unbind, R.id.btn_sendmsg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_bind:
                Intent intent = new Intent(this, MessageService.class);
                bindService(intent,serviceConnection2, Context.BIND_AUTO_CREATE);
                Toast.makeText(this, "我们都好", Toast.LENGTH_SHORT).show();
//                startService(intent);
                break;
            case R.id.btn_unbind:
                if (mBound) {
                    Log.e("zj", "onClick-->unbindService");
                    unbindService(serviceConnection2);
                    mBound = false;
                }
                break;
            case R.id.btn_sendmsg:
                sayHello(view);
                break;
        }
    }
}
